package cn.backpackerxl.dao.impl;

import cn.backpackerxl.dao.AdminDao;
import cn.backpackerxl.entity.Admin;
import cn.backpackerxl.util.DButils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: backpackerxl
 * @create: 2021/12/8
 * @filename: AdminDaoImpl
 **/
public class AdminDaoImpl implements AdminDao {
    private Connection cn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;
    private String sql;
    private Admin admin;

    @Override
    public Admin findByEmail(String email) {
        sql = "select * from t_admin where email = ?";
        return findByAdmin(email);
    }

    @Override
    public Admin findByPhone(String phone) {
        sql = "select * from t_admin where phone = ?";
        return findByAdmin(phone);
    }

    @Override
    public int addAdmin(Admin admin) {
        sql = "insert into t_admin values (id,?,?,?,?,?)";
        int i = 0;
        try {
            cn = DButils.getConnection();
            ps = cn.prepareStatement(sql);
            ps.setNString(1, admin.getName());
            ps.setNString(2, admin.getPasswd());
            ps.setNString(3, admin.getEmail());
            ps.setInt(4, admin.getSex());
            ps.setNString(5, admin.getPhone());
            i = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DButils.close(cn, ps);
        }
        return i;
    }

    /**
     * 通用查询方法
     *
     * @param args 查询参数
     * @return 查询结果
     */
    private Admin findByAdmin(String args) {
        try {
            cn = DButils.getConnection();
            ps = cn.prepareStatement(sql);
            ps.setNString(1, args);
            rs = ps.executeQuery();
            if (rs.next()) {
                int id = rs.getInt(1);
                String name = rs.getString(2);
                String passwd = rs.getString(3);
                String emails = rs.getString(4);
                int sex = rs.getInt(5);
                String phone = rs.getString(6);
                admin = new Admin(id, sex, name, passwd, emails, phone);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DButils.close(cn, ps, rs);
        }
        return admin;
    }
}
